<template>
    <el-dialog
      class="dialog companygoodsLog"
      v-model="visible"
      :draggable="true"
      title="位置选择"
      destroy-on-close
      style="border-radius: 4px;background-color: #ffffff"
      top="100px"
      width="50%">
        <div style="height:40px;width:100%;display: flex;align-items: center;">
            <el-select
                v-model="areaValue"
                filterable
                style='width:350px'
                remote
                reserve-keyword
                placeholder="请输入地址关键词"
                :remote-method="remoteMethod"
                :loading="loading"
                @change="currentSelect"
            >
                    <el-option
                    v-for="item in areaList"
                    :key="item.id"
                    :label="item.name"
                    :value="item"
                    class="one-text"
                >
                    <span style="float: left">{{ item.name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.district
                    }}</span>
                </el-option>
            </el-select>
        </div>
        <div id="container" style="height:500px;width:100%;margin-top:10px;"></div>
        <template #footer>
          <div class="dialog-footer">
            <div class="select-position">{{checkedForm.address}}</div>
            <div>
              <el-button @click="visible = false">关闭</el-button>
            <el-button type="primary" @click="confirmData">
            确定
            </el-button>
            </div>
           
          </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref,onMounted,onUnmounted } from 'vue'
import {ElMessage} from 'element-plus'
window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: `${import.meta.env.VITE_APP_AMAP_SECURITYJSCODE}`,
}
import AMapLoader from "@amap/amap-jsapi-loader";
const emits = defineEmits(['confirm'])
const visible:any = ref(false)
const areaList:any =ref([])
const areaValue = ref('')
let map:any = null
const loading:any = ref(false)
const checkedForm:any = ref({})
let autoComplete:any = null
let aMap:any = null
let geoCoder:any = null
const initMap = () => {
    AMapLoader.load({
    key: `${import.meta.env.VITE_APP_AMAP_KEY}`, // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Geocoder", "AMap.AutoComplete"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  }).then((AMap:any) => {
      aMap = AMap
      map = new AMap.Map("container", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
      });
      autoComplete = new AMap.AutoComplete({
      
      });
      geoCoder = new AMap.Geocoder({
        radius: 1000, //范围，默认：500
      });
      map.on('click',(e:any)=>{
        console.log(e)
        addmark(e.lnglat.getLng(),e.lnglat.getLat(),AMap)
        
      })
    })
    .catch((e) => {
      console.log(e);
    });
}
let marker:any = null
const addmark = (lng:any,lat:any,AMap:any) => {
    marker && removeMarker()
    marker = new AMap.Marker({
            position: new AMap.LngLat(lng,lat),
            zoom: 13
    });
    checkedForm.value.lng=lng
    checkedForm.value.lat=lat
    map.add(marker);
    map.setCenter([lng,lat],'',500);
    geoCoder.getAddress([lng,lat], (status:any, result:any) => {
            if (status === 'complete' && result.regeocode) {
               checkedForm.value.formattedAddress=result.regeocode.formattedAddress
               let addressComponent=result.regeocode.addressComponent
               checkedForm.value.addressComponent=addressComponent
               checkedForm.value.address=addressComponent.township+addressComponent.street+addressComponent.streetNumber
            }
        });
}
 
const removeMarker = () => {
    map.remove(marker)
}
 
const remoteMethod = (searchValue:any) => {
    if (searchValue !== "") {
    setTimeout(() => {
      autoComplete.search(searchValue, (status:any, result:any) => {
            if(result.tips?.length){
                areaList.value = result?.tips
				        currentSelect(areaList.value[0])
            }
        });
    }, 200);
    } else {
    
    }
}
 
 
const currentSelect = (val:any) => {
  console.log(val)
  if (val&&val.location) {
    areaValue.value = val.name
    checkedForm.value.lng = val.location?.lng
    checkedForm.value.lat = val.location?.lat
    addmark(val.location?.lng,val.location?.lat,aMap)
    map.setCenter([val.location?.lng,val.location?.lat],'',500);
    
  }
    
   
}
 
const confirmData = () => {
    if(!checkedForm.value?.lat || !checkedForm.value?.lng){
        return ElMessage.error('请选择地址')
    }
    emits('confirm',checkedForm.value)
    visible.value = false
    areaValue.value = ''
    map?.destroy();
}
const open = (address?:String) => {
  checkedForm.value = {}
	areaValue.value = address
    initMap()
    visible.value = true

	setTimeout(function(){
		remoteMethod(areaValue.value)
	},1000)
	
}
 
defineExpose({
    open
})
onMounted(()=>{
    
})
onUnmounted(() => {
  map?.destroy();
});
</script>

<style>
.dialog-footer{
  display: flex;
  flex-direction: row;
  justify-content: end;
  align-items: center;
}
.select-position{
  margin-right: 10px;
}
</style>